package db;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import db.*;

public class UserAdded extends HttpServlet {
	public void doPost(HttpServletRequest request,HttpServletResponse response)
										throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		DatabaseConnector DBConnect = new DatabaseConnector(DatabaseConnector.getDatabaseType());


		out.println("<html><head><title>User Addition -- Result</title>");
		out.println("<script type=\"text/javascript\" src=\"../userManager.js\"></script>");
		out.println("</head><body>");


		String[] in = {"*"};
		Object[] check = DBConnect.selectSQL("Users",in,"username",request.getParameter("username")); // Retrieve connection information
		try{
			if (check[0].equals("null")){ }//triggers catch if does not exist
			out.println("<body onload=directToAdd(\"?"
				+ "username=" + request.getParameter("username")
				+ "&password=" + request.getParameter("password")
				+ "&email=" + request.getParameter("email")
				+ "&groups=" + request.getParameter("groups")
				+ "&loadCase=existent"
				+ "\")>Redirecting you to Add New User...</body></html>");
		} catch (NullPointerException npe) {
			//start of changes------------------------------------------------------------------------------
			String pwd = null;
			try{
				java.security.MessageDigest md5Digest = java.security.MessageDigest.getInstance("MD5");
				byte[] bytes = request.getParameter("password").getBytes();
				pwd = new String(md5Digest.digest(bytes));
			} catch (java.security.NoSuchAlgorithmException nsae) {
				System.out.println(nsae);
			}
			in = new String[]{ (request.getParameter("username")),pwd }; //end of changes-----------------------
			String[] params = {"username","password"};
			DBConnect.insertSQL("Users",params,in);

			in = new String[] {request.getParameter("username"),request.getParameter("email")};
			params[1] = "email";
			DBConnect.insertSQL("User_Info",params,in);

			//insert groups
			String reqGroups = request.getParameter("groups");
			if (!reqGroups.equals("")) {
				String[] groups = reqGroups.split(";");
				params[1] = "role";
				for (int i=0;i<groups.length;i++){
					in = new String[]{ request.getParameter("username"),groups[i] };
					DBConnect.insertSQL("User_Roles",params,in);
				}
			}
			out.println("<h3>User '"+ request.getParameter("username") +"' successfully added!</h3>");
			out.println("<a href=\"ListUsers\">Return to User Listing</a></body></html>");
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
		doPost(request, response);
	}
}